
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class BarraProgresso {

    private String nickname;
    private DefaultListModel lista = new DefaultListModel();
    ;
    private int porta;
    private String ip;

    public static void main(String[] args) {
        //new BarraProgresso();
    }

    public BarraProgresso(String nickname, DefaultListModel lista) {
        this.nickname = nickname;
        this.lista = lista;
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                new BarraProgresso.BackgroundWorker().execute();

            }
        });
    }

    public class BackgroundWorker extends SwingWorker<Void, Void> {

        private JProgressBar pb;
        private JDialog dialog;

        public BackgroundWorker() {
            addPropertyChangeListener(new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                        if (dialog == null) {
                            dialog = new JDialog();
                            dialog.setTitle("Conectando");
                            dialog.setLayout(new GridBagLayout());
                            dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                            dialog.setResizable(false);
                            GridBagConstraints gbc = new GridBagConstraints();
                            gbc.insets = new Insets(2, 2, 2, 2);
                            gbc.weightx = 1;
                            gbc.gridy = 0;
                            dialog.add(new JLabel("Tentando reconectar-se ao servidor..."), gbc);
                            pb = new JProgressBar();
                            gbc.gridy = 1;
                            dialog.add(pb, gbc);
                            dialog.pack();
                            dialog.setLocationRelativeTo(null);
                            dialog.setVisible(true);
                        }
                        pb.setValue(getProgress());
                    }
                }
            });
        }

        @Override
        protected void done() {
            if (dialog != null) {
                dialog.dispose();
                try {
                    lerArquivo();
                    Socket socket = new Socket(ip, porta);
                    PrintStream saida = new PrintStream(socket.getOutputStream());
                    saida.println(nickname.toUpperCase());
                    Chat chat;
                    chat = new Chat(socket, nickname, lista);
                    chat.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    int answer = JOptionPane.showConfirmDialog(null, "A conexão com o servidor foi perdida. Tentar reconectar?");
                    if (answer == JOptionPane.YES_OPTION) {
                        new BarraProgresso(nickname, lista);
                    } else if (answer == JOptionPane.NO_OPTION) {
                        System.exit(0);
                    } else {
                        System.exit(0);
                    }

                }

            }
        }

        @Override
        protected Void doInBackground() throws Exception {
            for (int index = 0; index < 70; index++) {
                setProgress(index);
                Thread.sleep(70);
            }
            return null;
        }
    }

    public void lerArquivo() throws IOException {
        File arquivo = new File("config.txt"); //se não existir, lança exception  
        FileReader fr;
        String linha;
        try {
            fr = new FileReader(arquivo);
            BufferedReader in = new BufferedReader(new FileReader("config.txt"));
            int line = 0;
            HashMap<Integer, String> lines = new HashMap<Integer, String>();
            while ((linha = in.readLine()) != null) {
                lines.put(line, linha);
                line++;
            }
            in.close();
            ip = lines.get(0);
            porta = Integer.parseInt(lines.get(1));
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao carregar as configurações");
            //Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
